<?php

namespace backend\controllers;

use yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use backend\models\service\NovelService as Novel;
use backend\behaviors\NovelBehavior;
use backend\models\service\TweetService as Tweet;
use backend\models\service\Chapter;
use backend\models\service\Charge;
use yii\data\ActiveDataProvider;
use backend\models\service\CateService as Cate;
use backend\lib\Helper;
use yii\filters\VerbFilter;
use yii\web\Response;

class NovelController extends Controller {
    
    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                    ],
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    '*' => ['get'],
                    'ajax-get-category' => ['post'],
                    'post-up-cate' => ['post'],
                    'extend' => ['get','post'],
                    'up-novel' => ['post'],
                    'down-novel' => ['post'],
                    'charge-setting' => ['post','get'],
                    'cate-update' => ['post','get'],
                    'charge-setting-batch' => ['post'],
                    'post-up-cate-batch' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * Lists all Company models.
     * @return mixed
     */
    public function actionIndex() {
//        if(!Yii::$app->authManager->checkAccess(Yii::$app->user->id,'novel.index')){
//            return $this->redirect('/site/index');
//        }
        $model = new Novel;
        $model->attachBehavior('novel', new NovelBehavior);
        $model->load(Yii::$app->request->queryParams);
        $datas = $model->list_for_index();
        //增值标准
        $charge = \backend\models\novel\NovelCharge::getAllCharge();
        //全部分类
        $category = \backend\models\novel\NovelCategory::getAllCategory();
        return $this->render('index', [
            'searchModel' => $model,
            'dataProvider' => $model->list_for_index(),
            'charge' => $charge,
            'category' => $category,
            'select' => Yii::$app->request->queryParams,
        ]);
    }

    /**
     * 分发推广第一步
     */
    public function actionExtend($id) {
        $this->layout = false;
        $model = new Tweet();
        $data = [];
        if ($model->load(Yii::$app->request->post())) {
            $request = Yii::$app->request->post('TweetService');
            $model->tweet_sn = Tweet::uniqidSn();
            $model->op_id = $request['op_id'];
            $model->novel_id = $request['novel_id'];
            $model->op_name = $request['op_name'];
            $model->channel_id = $request['channel_id'];
            $model->channel_name = $request['channel_name'];
            $model->chapter_id = $request['chapter_id'];
            $model->platform = $request['platform'];
            $model->is_force_focus_wechat = $request['is_force_focus_wechat'];
            $model->is_force_focus_chapter = $request['is_force_focus_chapter'];
            $model->create_time = date('Y-m-d H:i:s');
            $model->status = 0;
            if ($model->validate()) {
                $res = $model->save(false);
                if($res){
                    $id = $model->id;
                    $keyWordModel = new \backend\models\TweetKeyword();
                    $keyWordModel->name = $request['key_words'];
                    $keyWordModel->tweet_id = $id;
                    $keyWordModel->create_time = date('Y-m-d H:i:s');
                    $keyWordModel->save();
                }
                return $this->redirect('/tweet/update?id='.$id.'&act=novel');
            } else {
                print_r($model->getErrors());
                die;
            }
        } else {
             return $this->render('extend', [
                'model' => $model,
                'data'  => \backend\models\novel\Novel::getById($id),
                'id' => $id
            ]);
        }
    }

    /**
     * @param int $pid
     * @param int $typeid
     */
    public function actionSite($pid, $typeid = 0) {
        $model = new Admin();
        $model = $model->where(['pid' => $pid])->orderBy(['id' => SORT_ASC])->asArray()->all();

        if ($typeid == 2) {
            $aa = "--请选择渠道--";
        } 
        echo Html::tag('option', $aa, ['value' => 'empty']);
        foreach ($model as $value => $name) {
            echo Html::tag('option', Html::encode($name), array('value' => $value));
        }
    }
    
     /**
     * 查阅书籍
     */
    public function actionView($id,$c = 1) {
        $this->layout = false;
        $model = new Chapter();
        $novel = new Novel();
        $info = $novel->getNovelInfo($id);
//        var_dump($info['novel_pinyin']);
        
//        $content = file_get_contents($file); 
        $data = $model->getChapters($id);
        $cinfo = $model->getChaptersInfo($c);
        $url = "http://59.110.0.207:9604/".$info['novel_pinyin']."/".$info['novel_title']."/".$cinfo['chapter_name'].".txt";
        if(@fopen($url,'r')){
            $content = file_get_contents($url);
            $content = iconv("gb2312", "utf-8//IGNORE",$content);
            return $this->render('view', [
                'data' => $data,
                'id' => $id,
                'content' => $content
            ]);
        }else{
            return $this->render('view', [
                'data' => $data,
                'id' => $id,
                'content' => '暂无详情'
            ]);
        }
//        $url = "http://test.xinwei.com:88/uploads/txt/".$info['novel_pinyin']."/".$info['novel_title']."/".$cinfo['chapter_name'].".txt";
        
    }
    
    
    /**
     * 增值设定修改charge-setting
     */
    public function actionChargeSetting($id = 0) {
        $this->layout = false;
        $model = new Charge();
        return $this->render('charge-setting', [
            'model' => $model,
            'id' => $id
        ]);
        
    }
    /**
     * 增值设定修改(批量)
     */
    public function actionChargeSettingBatch() {
        $model = new Charge();
        $novel = new Novel();
        if(Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $ids = $post['ids'];
            if(is_array($ids)){
                if($post['model'] == 0){
                    $res = $novel->upChargeStatus($ids,1);
                }elseif($post['model'] > 0){
                    $info = $model->getChargeModelInfo($post['chapter'],$post['price']);
                    if($info){
                        $charge_id = $info['charge_id'];
                    }else{
                        $data = [
                            'charge_model' => $post['model'],
                            'charge_start_chapter' => $post['chapter'],
                            'charge_price' => $post['price'],
                            'novel_create_time' => date('Y-m-d H:i:s'),
                        ];
                        $charge_id = $model->addChargeModel($data,1);
                    }
                    $res = $novel->upChargeStatus($ids,$charge_id);
                }
                if($res){
                    echo json_encode(['status'=>0,'msg'=>'成功']);
                    exit;
                }else{
                    echo json_encode(['status'=>0,'msg'=>'失败']);
                    exit;
                }
            }else{
                $nid = $post['novel'];
                if($nid == 0){
                    $res = false;
                }else{
                    $info = $novel->getNovelInfo($nid);
                    if($post['model'] == 0 && !empty($info)){
                        $res = $novel->upChargeStatus($nid,1);
                    }elseif($post['model'] > 0){
                        $info = $model->getChargeModelInfo($post['chapter'],$post['price']);
                        if($info){
                            $res = $novel->upChargeStatus($nid,$info['charge_id']);
                        }else{
                            $data = [
                                'charge_model' => $post['model'],
                                'charge_start_chapter' => $post['chapter'],
                                'charge_price' => $post['price'],
                                'novel_create_time' => date('Y-m-d H:i:s'),
                                'novel_id' => $nid
                            ];
                            $res = $model->addChargeModel($data);
                        }
                    }
                }
                if($res){
                    echo json_encode(['status'=>0,'msg'=>'成功']);
                    exit;
                }else{
                    echo json_encode(['status'=>0,'msg'=>'失败']);
                    exit;
                }
            }
        }
    }
    
     /**
     * 分类/频道修改
     */
    public function actionCateUpdate($id = 0) {
//        $this->layout = false;
        $cate = new Cate();
        $nv_datas = $cate->getCateData(2);
        $nan_datas = $cate->getCateData(1);
        return $this->render('cate-update', [
            'nv_datas' => $nv_datas,
            'nan_datas' => $nan_datas,
            'id' => $id,
            'nums' => 1
        ]);
        
    }
    
    public function actionAjaxUpCate(){
        if(Yii::$app->request->isPost){
            $id = Yii::$app->request->post('id');
            var_dump($id);
            exit;
        }
    }
    
    
    public function actionPostUpCateBatch(){
        $cate = new Cate();
        $novel = new Novel();
        if(Yii::$app->request->isPost){
           if(Yii::$app->request->post()){
                $cid = Yii::$app->request->post('cid');
                $id = Yii::$app->request->post('id');
                $main_cate = $cate->getMainCate($cid);
                $res = $novel->upCate($id,$cid,$main_cate['cate_main']);
                if($res){
                    echo json_encode(['status'=>0,'msg'=>'成功']);
                    exit;
                }else{
                    echo json_encode(['status'=>0,'msg'=>'失败']);
                    exit;
                }
           } 
        }
    }


    protected function findModel($id) {
        if (($model = Novel::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    public function actionCate(){
        self::$_items = [];
        $data = static::find()->where(['cate_main' => $type])->asArray()->all();
        foreach ($data as $model) {
            self::$_items[$model['cate_id']] = $model['cate_name'];
        }
        return self::$_items;
        return $this->render('cate-update', [
            'dataProvider' => $data,
        ]);
    }
    
    /**
     * ajax获取分类
     */
    public function actionAjaxGetCategory()
    {
        $post = Yii::$app->request->post();
        $main = $post['main'];
        $list = \backend\models\novel\NovelCategory::getAllCategory(array('cate_main'=>$main));
        echo json_encode(array('status' => 0,'list' => $list));
    }
    
    
    /**
     * 上架操作
     */
    
    public function actionUpNovel(){
        if(Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $id_arr = explode(',',$post['ids']);
            $novel = new Novel();
            $res = $novel->bathUp($id_arr);
            if($res){
                echo "上架成功";
            }else{
                echo "上架失败";
            }
        }
    }
    /**
     * 上架操作
     */
    
    public function actionDownNovel(){
        if(Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $id_arr = explode(',',$post['ids']);
            $novel = new Novel();
            $res = $novel->bathDown($id_arr);
            if($res){
                echo "下架成功";
            }else{
                echo "下架失败";
            }
        }
    }
    
    
    
    public function actionAddAds(){
        
    }
}
